//
//  API+HandyJSON.swift
//  WZApp
//
//  Created by evol on 2018/7/2.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import Moya
import HandyJSON


extension Response {
    func mapModelList<T: HandyJSON>(_ type: T.Type) -> [T] {
        let jsonString = String(data: data, encoding: .utf8)
        let apiModel = JSONDeserializer<APIModel>.deserializeFrom(json: jsonString)!
        
        if let datas = apiModel.data as? Array<Dictionary<String, Any>> {
            return datas.compactMap({ T.deserialize(from: $0 ) })
        }
        return []
    }
}

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) -> T {
        let jsonString = String(data: data, encoding: .utf8)
        let apiModel = JSONDeserializer<APIModel>.deserializeFrom(json: jsonString)!
        
        if let data = apiModel.data as? Dictionary<String, Any> {
            return T.deserialize(from:data)!
        }
        print("API+HandyJson:mapModel error! no dictionry")
        return T()
    }
}


extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
    func mapModelList<T: HandyJSON>(_ type: T.Type) -> Single<[T]> {
        return flatMap { response -> Single<[T]> in
            return Single.just(response.mapModelList(T.self))
        }
    }
}

extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) -> Single<T> {
        return flatMap { response -> Single<T> in
            return Single.just(response.mapModel(T.self))
        }
    }
}
